package com.zx._03_并发.chapter_00_lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class ReentrantReadWriteDemo {

    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        WriteLock writeLock = lock.writeLock();
        ReadLock readLock = lock.readLock();
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 6; i++) {
            if (i % 2 == 0) {
                pool.execute(() -> {//只允许一个线程写入（其他线程既不能写入也不能读取）
                    writeLock.lock();//
                    try {
                        System.out.println("----------------");
                        String name = Thread.currentThread().getName();
                        System.out.println(name + "write>>>>");
                        Thread.sleep(1000L);
                        System.out.println(name + "write<<<<");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        writeLock.unlock();//
                    }
                });
            } else {
                pool.execute(() -> {
                    readLock.lock();//没有写入时，多个线程允许同时读（提高性能）。
                    try {
                        System.out.println("----------------");
                        String name = Thread.currentThread().getName();
                        System.out.println(name + "read>>>>");
                        Thread.sleep(1000L);
                        System.out.println(name + "read<<<<");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        readLock.unlock();//
                    }
                });
            }
        }
    }
}
